/**
 * Created by leiweibo on 6/28/15.
 */

'use strict'

var app = angular.module('homecontroller', []);

app.controller('HomeCtrl',
  function ($rootScope, $scope, $location, $window, $localStorage, Main) {



    $scope.signin = function () {
      var formData = {
        username: $scope.username,
        password: $scope.password
      }

      Main.signin(formData, function (res) {
        if (res.result == false) {
          $scope.error_msg = res.message;
        } else {
          //$localStorage.token = res.token;
          $window.sessionStorage.token = res.user.token;
          $window.sessionStorage.username = res.user.username;
          $window.sessionStorage.userid = res.user._id;
          $window.sessionStorage.role = res.user.role;

          if (res.user.hospital) {
            $window.sessionStorage.hospital = res.user.hospital._id;
            $window.sessionStorage.province = res.user.hospital.province;
          }
          $scope.username = res.user.username;
          $scope.userid = res.user.id;
          $window.location = "/";
        }
      }, function (data, status) {
        $scope.error_msg = data.message;
        $rootScope.error = 'Failed to signin';
      });
    };


    $scope.me = function (req, res) {
      Main.me(function (res) {
        $scope.myDetails = res;
      }, err('fetch detail'));
    };

    $scope.logout = function () {
      Main.logout(function (res) {
        if (res.result == true) {
          delete $window.sessionStorage.token;
          delete $window.sessionStorage.username
          delete $window.sessionStorage.province
          delete $window.sessionStorage.hospital
          delete $window.sessionStorage.role
          delete $scope.token;
          delete $scope.username;
          delete $scope.role;
          delete $scope.province;
          delete $scope.hospital;
          delete $scope.role;
          window.location = "#/signin"
        } else {
          alert(res.message);
        }
      }), function () {
        alert("Failed to logout!");
      };
    };
    $scope.token = $window.sessionStorage.token;
    $scope.username = $window.sessionStorage.username;
    $scope.role = $window.sessionStorage.role;
    //$scope.token = $localStorage.token;

    if ($window.sessionStorage.token) {
      window.location = "#/me";
      return;
    }

  })